package jsecurity.asym;

import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

import jsecurity.exceptions.KeyPairCreationException;

public class KeyPair 
{
	public static final int DEFAULT_KEY_SIZE = 2048;
	
	public static enum KeySize
	{
		K512, K1024, K2048, K4096
	}
	
	private PrivateKey privateKey;
	private PublicKey publicKey;
	
	public KeyPair(KeySize size) throws KeyPairCreationException
	{
		KeyPairGenerator generator;
		
		int keysize = (size == null) ? DEFAULT_KEY_SIZE : Integer.parseInt(size.toString().replace("K", "")); 
		
		try
		{
			generator = KeyPairGenerator.getInstance("RSA");
		} 
		catch(NoSuchAlgorithmException e) 
		{
			throw new KeyPairCreationException("The RSA security algorithm is not supported", e);
		}
		
        generator.initialize(keysize, new SecureRandom());
        
        java.security.KeyPair keypair = generator.generateKeyPair();
        this.privateKey = keypair.getPrivate();
        this.publicKey = keypair.getPublic();
	}
	
	public PrivateKey getPrivateKey()
	{
		return this.privateKey;
	}
	
	public PublicKey getPublicKey()
	{
		return this.publicKey;
	}
}
